#!/bin/bash

# 切换到脚本所在目录
cd "$(dirname "$0")"

echo "================================================"
echo "    建党在线系统 - Docker 一键启动"
echo "================================================"
echo ""
echo "📂 当前目录: $(pwd)"
echo ""

# 检查 docker-compose.yml 是否存在
if [ ! -f "docker-compose.yml" ]; then
    echo "❌ 错误: 找不到 docker-compose.yml 文件"
    echo "   请确保在项目根目录运行此脚本"
    exit 1
fi

echo "🐳 正在检查 Docker 环境..."
echo ""

# 检查 Docker daemon 是否运行
if ! docker info &> /dev/null; then
    echo "❌ 错误: Docker daemon 未运行"
    echo ""
    echo "📝 解决方案："
    echo "   1. 打开 Launchpad"
    echo "   2. 搜索并打开 'Docker'"
    echo "   3. 等待 Docker 图标显示为绿色（运行中）"
    echo "   4. 重新运行此脚本"
    echo ""
    echo "或使用命令启动："
    echo "   open -a Docker"
    echo ""
    exit 1
fi

echo "✓ Docker daemon 正在运行"

# 检测 Docker Compose 命令
if command -v docker &> /dev/null && docker compose version &> /dev/null 2>&1; then
    DOCKER_COMPOSE="docker compose"
    echo "✓ 使用: docker compose (Docker Desktop 内置)"
elif command -v docker-compose &> /dev/null; then
    DOCKER_COMPOSE="docker-compose"
    echo "✓ 使用: docker-compose (独立版本)"
else
    echo "❌ 错误: 未找到 Docker Compose"
    echo "   请安装 Docker Desktop: https://www.docker.com/products/docker-desktop/"
    exit 1
fi

echo ""

# 停止并删除旧容器（如果存在）
echo "📦 清理旧容器..."
$DOCKER_COMPOSE down 2>/dev/null

echo ""
echo "🔨 构建并启动服务..."
echo ""

# 构建并启动所有服务
$DOCKER_COMPOSE up --build -d

if [ $? -eq 0 ]; then
    echo ""
    echo "================================================"
    echo "           🎉 启动成功！"
    echo "================================================"
    echo ""
    echo "📍 服务访问地址："
    echo "   ├─ 后端API:    http://localhost:8080/springboot1i659"
    echo "   ├─ 管理端:     http://localhost:8088"
    echo "   └─ 用户端:     http://localhost:8089"
    echo ""
    echo "👤 默认账号："
    echo "   管理端: java1234 / 123456"
    echo "   用户端: 党员账号1 / 123456"
    echo ""
    echo "💡 常用命令："
    echo "   查看日志:    $DOCKER_COMPOSE logs -f"
    echo "   停止服务:    $DOCKER_COMPOSE down"
    echo "   重启服务:    $DOCKER_COMPOSE restart"
    echo "   查看状态:    $DOCKER_COMPOSE ps"
    echo ""
    echo "⏳ 提示: 首次启动需要等待5-10分钟（构建）"
    echo ""
else
    echo ""
    echo "❌ 启动失败，请检查错误信息"
    echo ""
    exit 1
fi

